package com.jichaoyun.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jichaoyun.common.model.Result;
import com.jichaoyun.common.utils.ExcelStyleUtils;
import com.jichaoyun.model.entity.Role;
import com.jichaoyun.dao.mapper.RoleMapper;
import com.jichaoyun.model.vo.RoleIdName;
import com.jichaoyun.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangzhen
 * @since 2023-11-03
 */
@RestController
@Api(tags = {"角色接口列表"})
@RequestMapping("/sys/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @Autowired
    private RoleMapper roleMapper;

    @ApiOperation("角色管理，角色注册")
    @PostMapping("/addRole")
    public Result<Object> addRole(@RequestBody Role role) {//@RequestBody是做json字符串的转换
//        System.out.println(role);
        return roleService.addRole(role);
    }

    @ApiOperation("角色管理，查询角色列表")
    @GetMapping("/getList")
    public Result<Map<String,Object>> getRoleList(@RequestParam(value = "pageNo") Long pageNo,
                                                  @RequestParam(value = "pageSize") Long pageSize){
         Map<String, Object> data= new HashMap<>();
         IPage<Role> roleIPage = roleService.getRoleList(pageNo,pageSize);
         List<Role> roleList = roleIPage.getRecords();
        for (Role role : roleList) {
            int num = roleService.getRoleNum(role.getRoleId());
            //获取其对应的用户数量
            role.setNum(num);
        }
         data.put("roleList",roleList);
         data.put("pages",roleIPage.getPages());
         data.put("total",roleIPage.getTotal());
        return Result.success(data);
    }

    @ApiOperation("角色管理，导出角色列表到excel")
    @GetMapping("/DownloadRoleList")
    public void DownloadRoleList(HttpServletResponse response) throws IOException {
        Map<String, Object> data= new HashMap<>();

        List<Role> roleList = roleService.getRoleList();

        for (Role role : roleList) {
            int num = roleService.getRoleNum(role.getRoleId());
            //获取其对应的用户数量
            role.setNum(num);
            if(role.getStatus()){
                role.setStatusStr("已启用");
            }else{
                role.setStatusStr("未启用");
            }
        }

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("角色信息导出表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());

            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), Role.class)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("sheet1")
                    .doWrite(roleList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSONUtils.toJSONString(map));
        }

    }



    @ApiOperation("查询所有角色Id和名称")
    @GetMapping("/getRoleIdNameList")
    public Result<List<RoleIdName>> getRoleList(){
        return Result.success(roleService.getAllRoleIdName());
    }


    @ApiOperation("角色修改回显，根据角色id查找角色全部信息")
    @GetMapping("/getRole/{id}")
    public Result<Role> getRoleById(@PathVariable("id") Integer id){
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    @ApiOperation("角色管理，修改角色状态")
    @PostMapping("/updateRoleStatus")
    public Result<?> updateStatus(@RequestParam(value = "roleId") Integer roleId){
        return roleService.updateStatus(roleId);
    }

    @ApiOperation("角色管理，修改角色信息，及其权限")
    @PostMapping("/updateRole")
    public Result<?> updateRole(@RequestBody Role role){
        roleService.updateRole(role);
        return Result.success("修改角色成功");
    }

    @ApiOperation("角色管理，删除角色及其对应权限")
    @DeleteMapping("/deleteRole/{id}")
    public Result<Role> deleteRoleById(@PathVariable("id") Integer id){
        roleService.deleteRoleById(id);
        return Result.success("删除角色成功");
    }


    @ApiOperation("测试")
    @GetMapping("/getAll")
    public Result<Map<String,Object>> getAll(){
        List<Role> roleList = roleMapper.getAll();
        Map<String, Object> data= new HashMap<>();
        data.put("roleList",roleList);
        return Result.success(data);
    }


}
